package sk.naive.talker.plugin;

import sk.naive.talker.*;

import java.net.*;
import java.io.*;

/**
 * PluginHelper.
 * <p/>
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.3 $ $Date: 2004/12/23 23:23:08 $
 */
public class PluginHelper {
	/**
	 *
	 * @param pluginName
	 * @return plugin or null if plugin file was not found
	 * @throws PluginException
	 */
	public TalkerPlugin createPlugin(String pluginName) throws PluginException {
		try {
			String pluginsDir = Main.getConfiguration().get(Consts.CONF_PLUGINS_DIR);
			if (pluginsDir == null || pluginsDir.length() == 0) {
				pluginsDir = ".";
			}
			if (!pluginsDir.endsWith(File.separator)) {
				pluginsDir += File.separator;
			}
			File pluginJarFile = new File(pluginsDir + "nt-plugin-" + pluginName + ".jar");
			if (!pluginJarFile.exists()) {
				return null;
			}
			ClassLoader classLoader = new URLClassLoader(new URL[] {pluginJarFile.toURI().toURL()});
			Configuration conf = new Configuration(classLoader.getResourceAsStream(pluginName + "-plugin.conf"));
			String className = conf.get(Consts.CONF_PLUGIN_MAIN_CLASS);

			Class cls = classLoader.loadClass(className);
			if (!(TalkerPlugin.class.isAssignableFrom(cls))) {
				throw new PluginException(className + " is not the plugin class!");
			}
			TalkerPlugin plugin = (TalkerPlugin) cls.newInstance();
			plugin.setConfig(conf);
			return plugin;
		} catch (NoClassDefFoundError e) {
			throw new PluginException(e);
		} catch (Exception e) {
			throw new PluginException(e);
		}
	}
}
